﻿using Microsoft.AspNetCore.Http;
using Neoit.Utils.Extensions;

namespace Infrastructure.WebApi
{
    /// <summary>
    /// 统一错误异常处理中间件类
    /// </summary>
    public class ErrorHandlingMiddlewareSimple
    {
        private readonly RequestDelegate next;
        public ErrorHandlingMiddlewareSimple(RequestDelegate next)
        {
            this.next = next;
        }
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                await _HandleExceptionAsync(context, ex);
            }
            finally
            {

            }
        }
        private static Task _HandleExceptionAsync(HttpContext context, Exception ex)
        {
            var result = new ErroResponse(ex.Message).ToJson();
            context.Response.StatusCode = 400;
            context.Response.ContentType = "application/json;charset=utf-8";
            return context.Response.WriteAsync(result);
        }
    }

    public class ErroResponse
    {
        public string Msg { get; set; }
        public ErroResponse(string msg)
        {
            Msg = msg;
        }
    }
}
